package com.gzu.finalwork.admin.service;

import com.gzu.finalwork.admin.mapper.AdminOrderMapper;
import com.gzu.finalwork.courier.mapper.CourierMapper;
import com.gzu.finalwork.entity.user.DeliveryOrders;
import com.gzu.finalwork.common.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminOrderService {

    @Autowired
    private AdminOrderMapper adminOrderMapper;
    
    @Autowired
    private CourierMapper courierMapper;

    /**
     * 获取所有订单信息（支持筛选、搜索、分页）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param orderStatus 订单状态筛选
     * @param keyword 模糊搜索关键词
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 订单列表
     */
    public Object getAllOrders(int pageNum, int pageSize, Integer orderStatus, 
                              String keyword, String startDate, String endDate) {
        try {
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;
            
            // 处理搜索关键词
            String searchKeyword = StringUtils.hasText(keyword) ? "%" + keyword.trim() + "%" : null;
            
            // 查询订单列表
            List<DeliveryOrders> orders = adminOrderMapper.selectOrdersWithFilter(
                offset, pageSize, orderStatus, searchKeyword, startDate, endDate);
            
            // 查询总数
            int total = adminOrderMapper.countOrdersWithFilter(
                orderStatus, searchKeyword, startDate, endDate);
            
            // 组装返回数据
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list", orders);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            resultData.put("totalPages", (int) Math.ceil((double) total / pageSize));
            
            return AjaxResult.success("获取订单列表成功", resultData);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单ID获取订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    public Object getOrderDetail(Long orderId) {
        try {
            DeliveryOrders order = adminOrderMapper.selectOrderById(orderId);
            if (order == null) {
                return AjaxResult.error(404, "订单不存在");
            }
            
            return AjaxResult.success("获取订单详情成功", order);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 更新订单状态
     * @param orderId 订单ID
     * @param orderStatus 新的订单状态
     * @param remark 备注
     * @return 更新结果
     */
    public Object updateOrderStatus(Long orderId, Integer orderStatus, String remark) {
        try {
            // 检查订单是否存在
            DeliveryOrders order = adminOrderMapper.selectOrderById(orderId);
            if (order == null) {
                return AjaxResult.error(404, "订单不存在");
            }
            
            // 验证状态值
            if (orderStatus < 0 || orderStatus > 4) {
                return AjaxResult.error(400, "无效的订单状态");
            }
            
            // 更新订单状态
            int result = adminOrderMapper.updateOrderStatus(orderId, orderStatus, remark);
            if (result > 0) {
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("orderId", orderId);
                resultData.put("oldStatus", order.getOrderStatus());
                resultData.put("newStatus", orderStatus);
                resultData.put("updateTime", LocalDateTime.now());
                
                return AjaxResult.success("订单状态更新成功", resultData);
            } else {
                return AjaxResult.error(500, "订单状态更新失败");
            }
        } catch (Exception e) {
            return AjaxResult.error(500, "更新订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单统计信息
     * @return 统计数据
     */
    public Object getOrderStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 总订单数
            int totalOrders = adminOrderMapper.countTotalOrders();
            statistics.put("totalOrders", totalOrders);
            
            // 各状态订单数
            statistics.put("waitingPickup", adminOrderMapper.countOrdersByStatus(0));    // 待揽收
            statistics.put("waitingShipment", adminOrderMapper.countOrdersByStatus(1));  // 待发货
            statistics.put("inTransit", adminOrderMapper.countOrdersByStatus(2));        // 运输中
            statistics.put("waitingDelivery", adminOrderMapper.countOrdersByStatus(3));  // 待签收
            statistics.put("completed", adminOrderMapper.countOrdersByStatus(4));        // 已完成
            
            // 今日订单数
            int todayOrders = adminOrderMapper.countTodayOrders();
            statistics.put("todayOrders", todayOrders);
            
            // 本月订单数
            int monthOrders = adminOrderMapper.countMonthOrders();
            statistics.put("monthOrders", monthOrders);
            
            return AjaxResult.success("获取订单统计成功", statistics);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取订单统计失败：" + e.getMessage());
        }
    }

    /**
     * 删除订单（软删除）
     * @param orderId 订单ID
     * @return 删除结果
     */
    @Transactional
    public Object deleteOrder(Long orderId) {
        try {
            // 检查订单是否存在
            DeliveryOrders order = adminOrderMapper.selectOrderById(orderId);
            if (order == null) {
                return AjaxResult.error(404, "订单不存在");
            }
            
            // 检查订单状态，已完成的订单才能删除
            if (order.getOrderStatus() != 4) {
                return AjaxResult.error(400, "只有已完成的订单才能删除");
            }
            
            // 1. 先删除配送员的接单信息
            int assignmentDeleteResult = courierMapper.deleteAssignmentByOrderId(orderId);
            
            // 2. 再删除订单
            int orderDeleteResult = adminOrderMapper.deleteOrder(orderId);
            
            if (orderDeleteResult > 0) {
                return AjaxResult.success("订单删除成功，同时清理了 " + assignmentDeleteResult + " 条配送分配记录");
            } else {
                return AjaxResult.error(500, "订单删除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error(500, "删除订单失败：" + e.getMessage());
        }
    }
} 